package com.cn.sl.server.config.traceid

import com.cn.sl.server.common.constant.Constant
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.dromara.hutool.core.data.id.IdUtil
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.slf4j.MDC
import org.springframework.lang.NonNull
import org.springframework.stereotype.Component
import org.springframework.web.servlet.HandlerInterceptor

@Component
class TraceIdInterceptor : HandlerInterceptor {

    val log: Logger = LoggerFactory.getLogger(TraceIdInterceptor::class.java)

    override fun preHandle(
        @NonNull request: HttpServletRequest,
        @NonNull response: HttpServletResponse,
        @NonNull handler: Any
    ): Boolean {
        val traceId = IdUtil.simpleUUID()
        MDC.put(Constant.TRACE_ID, traceId)
        log.info("请求：${request.requestURI}，生成traceId[${traceId}]")
        return true
    }

    override fun afterCompletion(
        @NonNull request: HttpServletRequest,
        @NonNull response: HttpServletResponse,
        @NonNull handler: Any,
        ex: Exception?
    ) {
        MDC.clear()
    }
}